import axios from 'axios'
import { getAccessToken } from '@/utils/userUtil'
const request = axios.create({
  baseURL: 'https://eternalavalon.top/webDesign',
  timeout: 10000
})
//拦截请求并在请求头上添加accessToken
//因此不需要再在每个请求里添加token参数
request.interceptors.request.use((config) => {
  const token = getAccessToken()
  if (token) {
    config.headers.accessToken = token
  }
  return config
})
//直接从AxiosResponse中获取data，存在错误则直接抛出
request.interceptors.response.use(
  (res) => {
    const data = res.data
    if (data.code != 200) {
      throw new Error(data.msg)
    }
    return data
  },
  (err) => {
    if (err.response) {
      console.log(err)
      if (err.response.status === 404) {
        throw new Error('404 Not Found')
      } else if (err.response.status === 500) {
        throw new Error('服务器错误')
      } else if (err.response.status === 401) {
        throw new Error('用户未登录')
      } else {
        throw new Error('未知错误')
      }
    } else if (err.request) {
      throw new Error('请求超时')
    } else {
      throw new Error('网络请求失败')
    }
  }
)
export default request
